<?php namespace App\Http\Controllers\Front;


use App\Models\Category;
use App\Models\Banners;
use App\Models\Employ;
use App\Models\EmployComments;
use App\Models\Ads;
use Illuminate\Support\Facades\Response;
use App\Models\Teaches;
use App\Models\EmployExt;
use App\Models\Tags;
use App\Models\ExaminationHistory;
use Illuminate\Support\Facades\Input;
use App\Models\Examination;


class EmployController extends MasterController 
{

    protected $catgory;
    protected $employHots;  //人气热点
    protected $workPlace;   //职场专栏
    protected $ads;         //广告
    protected $nav;         //当前焦点
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->catgory = Category::where(array('app'=>'employ','pid'=>0))->get();
        
        $this->employHots =Employ::with('exts')->join('employ_ext as eext', 'eext.news_id', '=', 'employ.id')
                            ->orderBy("eext.reading_num",'desc')
                            ->orderBy("eext.comment_num",'desc')
                            ->orderBy("eext.recommond_num",'desc')
                            ->skip(0)->take(7)->get();
        $this->workPlace=array();
        
        $this->ads = Ads::whereHas('getPositionName',function($query){
            $query->where('alias', '侧面');
        })->where(['app' => 'employ'])->skip(0)->take(3)->get();
        $this->nav = 1;
    }

    /**
     * Show the application dashboard to the user.
     *
     * @return Response
     */
    public function index()
    {
        // 分类导航
        $employ_cat = $this->getCategoryTree(0, false, 2, 'employ');
        $new_employ_cat = array_where($employ_cat, function($key, $value){
            return $key < 3;
        });
        //轮播图片
        $banners = Banners::where(array('app'=>'employ'))->orderBy('sort','asc')->orderBy('created_at','desc')->skip(0)->take(4)->get();

        //热门精华
        $hot_news = Employ::join('employ_ext as eext', 'eext.news_id', '=', 'employ.id')
                            ->orderBy("eext.recommond_num",'desc')->orderBy("eext.comment_num",'desc')
                            ->orderBy("eext.reading_num",'desc')->skip(0)->take(3)->get();

        /*热门公开课*/
        $teaches = Teaches::where(array('is_recommond'=>1,'is_validate'=>1))->orderBy('studys_num','desc')->orderBy('views_num','desc')
    	               ->orderBy('comments_num','desc')->orderBy('attention_num','desc')->orderBy('updated_at','desc')->take(4)->get();

        $employ = array();
        foreach ($this->catgory as $key=>$cate)
        {
            $employsql = Employ::whereIn('cat_id',$this->getSubCategory($cate->cat_id))
                                ->where(array('is_recommond'=>1,'is_validate'=>1))
                                ->orderBy('updated_at','desc')
                                ->skip(0);
            if($key==2)
                $employsql->take(6);
            else 
                $employsql->take(4);
            $employ[$cate->cat_id] = $employsql->get();
            
        }
        return view('front.employ.index')->with('emp_cates', $new_employ_cat)
                                   ->with('banners', $banners)
                                   ->with('hot_news', $hot_news)
                                   ->with('hotspot_news', $this->employHots)
                                   ->with('workplace', $this->workPlace)
                                   ->with('ads_img', $this->ads)
                                   ->with('category',$this->catgory)
                                   ->with('employ',$employ)
                                   ->with('hotclass', $teaches)
                                   ->with('nav',$this->nav);
    }

    /**
     * 就业指南详情页
     * @return [type] [description]
     */
    public function employList()
    {	
        $cateid = Input::get('cateid',0);
        $secondid = Input::get('secondid',0);
        $lastid = Input::get('lastid',0);
        $sort = Input::get('sort',0);
        $page = Input::get('page',1);
        $search = Input::get('kw','');
        $now_cate=collect();
            
        if(!empty($cateid) && $cateid != 0)
        {
            $subcateid = Category::with('childrenCates')->where('pid','=',$cateid)->get();
        }
        else 
        {
            $subcateid = collect();
        }

        //获取就业指南文章列表
        $query = Employ::with('user','attachment','exts');
        switch ($sort){
            case 1:  //浏览人数
                $query->join('employ_ext as eext', 'eext.news_id', '=', 'employ.id')->orderBy("eext.reading_num",'desc');
                break;
            case 2:  //评论人数
                $query->join('employ_ext as eext', 'eext.news_id', '=', 'employ.id')->orderBy('eext.comment_num','desc');

                break;
            case 3:  //收藏人数
                $query->join('employ_ext as eext', 'eext.news_id', '=', 'employ.id')->orderBy('eext.recommond_num','desc');
                break;
            default:  //综合排序
                $query->join('employ_ext as eext', 'eext.news_id', '=', 'employ.id')->orderBy("eext.reading_num",'desc')->orderBy("eext.comment_num",'desc')->orderBy("eext.recommond_num",'desc');
        }

        if(!empty($search))
        {
            $query->where('title','like','%'.$search.'%');
        }
        $query->where('is_validate','=',1);
		if($lastid > 0)
		{
		    $now_cate = Category::find($lastid);
		    $query->where('cat_id','=',$lastid);
		}
		elseif($secondid > 0)
		{
		    $now_cate = Category::find($secondid);
		    $query->whereIn('cat_id',$this->getSubCategory($secondid));
		}
        elseif ($cateid > 0)
        {
            $now_cate = Category::find($cateid);
            $query->whereIn('cat_id',$this->getSubCategory($cateid));
        }
        $employAll=$query->get();//不分页内容获取 by H
        $groupKey=array();
       foreach($employAll as $key=>$value){
           if(!empty($value->to_link)){
               $groupKey[]=$value->to_link;
           }
        }
        $groupKey=array_unique($groupKey);
        //header("content-type:text/html;charset=utf-8");
        //回合合并
        if(!empty( $groupKey)&&!empty($cateid)){
            $xili=collect();
            foreach($groupKey as $key=>$value){
                $oop=clone $query;
                $xili[]= $oop->where('to_link',$value )->orderBy('created_at','ASC')->first();  //dd($xili);
            }
            $danYe=$query->where('to_link',null)->get();
            $employListE=$xili->merge($danYe);
            $employ_num = count($employListE);
            $take = 10;
            $skip = ($page-1)*$take;
            $employList=array_slice($employListE->all(),$skip,$take);
        }else{
            $employ_num = count($query->get());
            $take = 10;
            $skip = ($page-1)*$take;
            $employList=$query->skip($skip)->take($take)->get();
        }
        if(\Illuminate\Support\Facades\Request::ajax())
		{
		    if(count($employList)>0){
    		    foreach ($employList as &$emp){
    		        $emp->publish_time = date('Y年m月d日 H:i',strtotime($emp->created_at));
    		        $emp->description =  str_limit(strip_tags($emp->description),200);
    		    }
		        return $this->formatJson('success','获取数据成功！',$employList,'',$page+1);
		    }else{ 
		        return $this->formatJson('error','没有更多数据...');
		    }
		}
		else 
		{
            $mianbaoxie = $this->mianbaoxie('employ', $cateid, $secondid, $lastid, count($now_cate)>0?$now_cate->cat_id:0,'就业指南');		
            return view('front.employ.list')->with('ads_img', $this->ads)->with('employ_num',$employ_num)
                                            ->with('hots_employ', $this->employHots)
                                            ->with('workplace',$this->workPlace)
                                            ->with('now_cate',$now_cate)
                                            ->with('cateid',$cateid)
                                            ->with('secondid',$secondid)
                                            ->with('lastid',$lastid)
                                            ->with('sort',$sort)
                                            ->with('subcateid',$subcateid)
                                            ->with('mianbaoxie',$mianbaoxie)
                                            ->with('category',$this->catgory)
                                            ->with("pages",$page+1)
                                            ->with('employList',$employList)
                                            ->with('nav',$this->nav);
		}
    }
	
	/**
	 * 就业指南二级页面
	 */
	public function show($id){

        if(!empty($this->user)){
            $result = Employ::with('exts')->where(['user_id'=>$this->user->id,'is_validate'=>0,'id'=>$id])->orWhere(['user_id'=>$this->user->id,'is_validate'=>2,'id'=>$id])->orWhere(['is_validate'=>1,'id'=>$id])->first();
        }else{
            $result=Employ::with('exts')->where(['is_validate'=>1,'id'=>$id])->first();
        }
        $employSet=collect();
    if(!empty($result->to_link)){
        $employSet =Employ::where("to_link",$result->to_link)
            ->orderBy('created_at','desc')
            ->orderBy("display_order",'desc')
            ->take(10)
            ->get();
    }


        //dd( $employSet);

       // dd($result->to_link);
		if(empty($result))
		    abort(404);
		$exts = EmployExt::findOrNew($id);
		$exts->incrementAdd('reading_num',1);

		$secondid = 0;
		$lastid = 0;

		if(count($result->category)>0)
		{
		   $secondid=$result->category->pid;
		   if(count($result->category->parentCate)>0)
		   {
		       $lastid = $result->category->parentCate->pid;
		   }
		}

		$ucollect = $this->isCollected('employ', $result->id);
		if(!empty($ucollect))
		{
		    $result->is_collect = 1;
		}
		else 
		{
		    $result->is_collect = 0;
		}
		$mianbaoxie = $this->mianbaoxie('employ', $lastid,$secondid,$result->cat_id , $id, '就业指南',$result->title,'show');

        $comments = EmployComments::with(['childComments'=>function ($query){
                $query->orderBy('created_at','desc');
            }])->where(array('to_comment_id'=>0,'employ_id'=>$id))->orderBy('created_at','desc')->get();
        $employTags = collect();
        $employTags = array();
        foreach ($result->tags as $etags)
        {
            $employTags[] = Tags::where('tags_id','=',$etags->tags_id)->first()->tags_name;
        }
        $questions = collect();
        if(count($result->examination)>0)
        {
            $questions = $result->examination->questions;
        }
        $isToDelivery = 0;


        if(!empty($this->user))
        {
            $history = ExaminationHistory::where(['app'=>'employ','job_id'=>$result->id,'user_id'=>$this->user->id])->first();
            if(!empty($history))
            {
                $examination = Examination::find($history->examination_id);
                if($history->score >= $examination->score_limit)
                    $isToDelivery = 1;
                else 
                    $isToDelivery = 2;
                }
                else
                {
                        $isToDelivery = 0;
                }
        }
        //选择模板
        if($result->exts->template_id == 'goodnice')
        {
            $result->content = unserialize($result->content);
            $viewPath = 'front.employ.showlast';
        }
        else
        {
            $viewPath = 'front.employ.show';
        }
        return view($viewPath)->with('ads_img', $this->ads)->with('hots_employ', $this->employHots)
            ->with('workplace',$this->workPlace)->with('result',$result)->with('employTags',$employTags)
            ->with('emp_id',$id)->with('mianbaoxie',$mianbaoxie)->with('comments',$comments)
            ->with('nav',$this->nav)->with('questions',$questions)->with('app','employ')
            ->with('isToDelivery',$isToDelivery)
            ->with('employSet',$employSet);
	}

    public function showlist($id)
    {

        if(!empty($this->user)){
            $result = Employ::with('exts')->where(['user_id'=>$this->user->id,'is_validate'=>0,'id'=>$id])->orWhere(['user_id'=>$this->user->id,'is_validate'=>2,'id'=>$id])->orWhere(['is_validate'=>1,'id'=>$id])->first();
        }else{
            $result=Employ::with('exts')->where(['is_validate'=>1,'id'=>$id])->first();;
        }
        if(empty($result))
            abort(404);

       // echo "你好";
        return view('front.employ.showlist')
            ->with('result', $result);


    }


}
